import {Tabs, message, Button, Divider, Popconfirm} from 'antd'
import React, { useState, useRef, useEffect } from 'react'
import { PageHeaderWrapper } from '@ant-design/pro-layout'
import ProTable, { ProColumns, ActionType } from '@ant-design/pro-table'
import { connect, Link } from 'umi'
import { queryAllocationList,getAllsalaryGroup,updateEmployeeSalaryGroup,findSalaryUnit,delSalaryGroup,logoutSalaryDistribution} from '../service'
import {salaryAdjustmentTypeList} from "@/utils/constant";
import moment from 'moment'
import CreateForm from './components/CreateForm';
import LogoutSalaryGroup from './components/LogoutSalaryGroup';

const { TabPane } = Tabs;

const TableList = ({}) => {
  const actionRef = useRef();
  const alreadyActionRef2 = useRef();
  const [isDistribute,setIsDistribute] = useState("0");
  const [salaryGroup,setSalaryGroup] = useState([]);
  const [payrollUnit,setPayrollUnit] = useState([]);
  const [done, setDone] = useState(false);
  const [visible, setVisible] = useState(null);
  const [current,setCurrent] = useState();
  const [operateType,setOperateType] = useState(null);
  const [logoutVisible,setLogoutVisible] = useState(false);

  useEffect(() => {
    getAllsalaryGroup().then(res => setSalaryGroup(res));
    findSalaryUnit().then(res => setPayrollUnit(res.list));
  }, []);


  const columns = [
    {
      title: '工号',
      dataIndex: 'code',
      key:'code',
      hideInSearch: true,
    },
    {
      title: '姓名',
      dataIndex: 'name',
      key:'name',
      render: (item, record) => (
        <Link to={`/info/details/${record.oid}`}>{item}</Link>
      ),
    },
    {
      title: '变动类型',
      dataIndex: 'type',
      hideInSearch: true,
      valueEnum: {
        0: { text: salaryAdjustmentTypeList[0].label},
        1: { text: salaryAdjustmentTypeList[1].label},
        2: { text: salaryAdjustmentTypeList[2].label},
        3: { text: salaryAdjustmentTypeList[3].label},
        4: { text: salaryAdjustmentTypeList[4].label},
        5: { text: salaryAdjustmentTypeList[5].label},
        6: { text: salaryAdjustmentTypeList[6].label},
        7: { text: salaryAdjustmentTypeList[7].label},
      },
    },
    {
      title: '公司名称',
      dataIndex: 'orgname',
      key:'orgname',
      hideInSearch: true,
    },
    {
      title: '部门名称',
      dataIndex: 'unitname',
      key:'unitname',
      hideInSearch: true,
    },
    {
      title: '岗位名称',
      dataIndex: 'jobname',
      key:'jobname',
      hideInSearch: true,
    },
    {
      title: '原薪资组',
      dataIndex: 'beforeSalaryGroupId',
      key:'beforeSalaryGroupId',
      hideInSearch: true,
      render:(text,record) => {
        return record.oidSalaryGroupDto && record.oidSalaryGroupDto.cname
      }
    },
    {
      title: '原发薪单位',
      dataIndex: 'beforePayrollUnit',
      key:'beforePayrollUnit',
      hideInSearch: true,
      render: (text,record) => {
        return record.oidSalaryUnitDto && record.oidSalaryUnitDto.cname
      },
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      hideInSearch: true,
      render: (text,record) => {
        return text !== '-' ? moment(text).format('YYYY-MM-DD') : ''
      },
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (item, record) => (
        <>
          <a onClick={(e) => assign(e, record)}>分配</a>
          <Divider type="vertical"/>
          <Popconfirm title="是否确定删除？" placement="leftBottom" cancelText='取消' okText='确认' onConfirm={() => deleteSalaryGroup(record.id)}>
            <a>删除</a>
          </Popconfirm>
        </>
      ),
    },
  ];
  const alreadyColumns = [
    {
      title: '工号',
      dataIndex: 'code',
      hideInSearch: true,
    },
    {
      title: '姓名',
      dataIndex: 'name',
      width:60,
      render: (item, record) => (
        <Link to={`/info/details/${record.oid}`}>{item}</Link>
      ),
    },
    {
      title: '变动类型',
      dataIndex: 'type',
      hideInSearch: true,
      valueEnum: {
        0: { text: salaryAdjustmentTypeList[0].label},
        1: { text: salaryAdjustmentTypeList[1].label},
        2: { text: salaryAdjustmentTypeList[2].label},
        3: { text: salaryAdjustmentTypeList[3].label},
        4: { text: salaryAdjustmentTypeList[4].label},
        5: { text: salaryAdjustmentTypeList[5].label},
        6: { text: salaryAdjustmentTypeList[6].label},
        7: { text: salaryAdjustmentTypeList[7].label},
      },
    },
    {
      title: '公司名称',
      dataIndex: 'orgname',
      hideInSearch: true,
    },
    {
      title: '部门名称',
      dataIndex: 'unitname',
      hideInSearch: true,
    },
    {
      title: '岗位名称',
      dataIndex: 'jobname',
      hideInSearch: true,
    },
    {
      title: '原薪资组',
      dataIndex: 'oidPayrollUnitId',
      hideInSearch: true,
      render:(text,record) => {
        return record.oidSalaryGroupDto && record.oidSalaryGroupDto.cname
      }
    },
    {
      title: '原发薪单位',
      dataIndex: 'beforePayrollUnit',
      key:'beforePayrollUnit',
      hideInSearch: true,
      render: (text,record) => {
        return record.oidSalaryUnitDto && record.oidSalaryUnitDto.cname
      },
    },
    {
      title: '变更后薪资组',
      dataIndex: 'salaryGroupId',
      key:'salaryGroupId',
      hideInSearch: true,
      render:(text,record) => {
        return record.salaryGroupDto && record.salaryGroupDto.cname
      }
    },
    {
      title: '变更后发薪单位',
      dataIndex: 'payrollUnit',
      key:'payrollUnit',
      hideInSearch: true,
      render: (text,record) => {
        return record.salaryUnitDto && record.salaryUnitDto.cname
      },
    },
    {
      title: '分配时间',
      dataIndex: 'distributionTime',
      hideInSearch: true,
      render: (text,record) => {
        return text !== '-' ? moment(text).format('YYYY-MM-DD') : ''
      },
    },
    {
      title: '操作人',
      dataIndex: 'distributionName',
      hideInSearch: true,
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      hideInSearch: true,
      render: (text,record) => {
        return text !== '-' ? moment(text).format('YYYY-MM-DD') : ''
      },
    },
  ];

  const callback = (key) => {
    setIsDistribute(key)
    if(key === '0'){
      actionRef.current &&  actionRef.current.reload();
    }else{
      alreadyActionRef2.current && alreadyActionRef2.current.reload();
    }
  };

  const deleteSalaryGroup = (id) => {
    delSalaryGroup(id).then(res =>{
      if(res.flag) {
        message.success('删除成功！');
        actionRef.current.reload()
      } else {
        message.error(res.error);
      }
    })
  };

  const assign = (e, record) =>{
    setVisible(true);
    setCurrent(record);
    setOperateType('update');
  };

  const addAssign = () => {
    setVisible(true);
    setCurrent(null);
    setOperateType('add');
  };

  const handleCancel = () => {
    setVisible(false);
    setLogoutVisible(false);
  };

  const handleSubmit = (values) => {
    setDone(true);
    setVisible(false);
    updateEmployeeSalaryGroup({...values, distributionTime:moment(values.distributionTime).format('YYYY-MM-DD')}).then(res=>{
      if(res.flag) {
        message.success('薪资组分配成功！');
        actionRef.current.reload()
      } else {
        message.error(res.error)
      }
    })
  };

  const handleLogoutSubmit = (values) => {
    logoutSalaryDistribution(values).then(res => {
      if(res.flag) {
        message.success('薪资组分配成功！');
        actionRef.current.reload()
      } else {
        message.error(res.error)
      }
      setLogoutVisible(false);
    });
  };

  return (
    <PageHeaderWrapper>
      <Tabs animated={false} defaultActiveKey="0" onChange={callback}>
        <TabPane tab="未分配" key="0">
          <ProTable
            actionRef={actionRef}
            rowKey="oid"
            request={(params) => queryAllocationList(params,isDistribute)}
            columns={columns}
            toolBarRender={(action, { selectedRows }) => [
              <Button key={0} type="primary" onClick={() => addAssign()}>分配薪资组</Button>,
              <Button key={1} danger onClick={() => setLogoutVisible(true)}>注销薪资组</Button>,
            ]}
          />
          <CreateForm
            salaryGroup={salaryGroup}
            payrollUnit={payrollUnit}
            operateType={operateType}
            current={current}
            visible={visible}
            onCancel={handleCancel}
            onSubmit={handleSubmit}
          />
          <LogoutSalaryGroup
            visible={logoutVisible}
            onCancel={handleCancel}
            onSubmit={handleLogoutSubmit}
          />
        </TabPane>
        <TabPane tab="已分配" key="1">
          <ProTable
            actionRef={alreadyActionRef2}
            rowKey="oid"
            request={(params) => queryAllocationList(params,isDistribute)}
            columns={alreadyColumns}
          />
        </TabPane>
      </Tabs>
    </PageHeaderWrapper>
  )
}

export default connect(() => ({
}))(TableList)
